from django.db import models
from django.contrib.auth.models import User


class VideoTask(models.Model):
    """视频生成任务模型"""
    # 状态选择
    STATUS_CHOICES = [
        ('queued', '排队中'),
        ('running', '运行中'),
        ('succeeded', '成功'),
        ('failed', '失败'),
    ]
    
    # 分辨率选择
    RESOLUTION_CHOICES = [
        ('480p', '480p'),
        ('720p', '720p'),
        ('1080p', '1080p'),
    ]
    
    # 宽高比选择
    ASPECT_RATIO_CHOICES = [
        ('16:9', '16:9'),
        ('9:16', '9:16'),
        ('1:1', '1:1'),
        ('4:3', '4:3'),
        ('21:9', '21:9'),  # 添加21:9选项
    ]
    
    # 时长选择（3-12秒）
    DURATION_CHOICES = [
        (3, '3秒'),
        (5, '5秒'),  # 添加5秒选项
        (6, '6秒'),
        (9, '9秒'),
        (10, '10秒'),  # 添加10秒选项
        (12, '12秒'),
    ]
    
    # 必存字段：关联用户、任务核心信息
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="发起用户")
    volc_task_id = models.CharField(max_length=255, unique=True, verbose_name="火山任务ID")  # 查进度用
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='queued',
        verbose_name="任务状态"
    )
    video_url = models.TextField(blank=True, null=True, verbose_name="视频链接")  # 改为TextField支持长URL
    error_msg = models.TextField(blank=True, null=True, verbose_name="失败原因")  # 失败了查原因
    
    # 用户输入字段
    prompt = models.TextField(max_length=200, verbose_name="文字提示词")  # 存您输入的"生成描述"
    resolution = models.CharField(
        max_length=10,
        choices=RESOLUTION_CHOICES,
        default='480p',  # 修改为最便宜的480p
        verbose_name="分辨率"
    )
    aspect_ratio = models.CharField(
        max_length=10,
        choices=ASPECT_RATIO_CHOICES,
        default='21:9',  # 修改为最便宜的21:9
        verbose_name="宽高比"
    )
    duration = models.IntegerField(
        choices=DURATION_CHOICES,
        default=5,  # 修改为最便宜的5秒
        verbose_name="时长（秒）"
    )
    frame_rate = models.IntegerField(default=24, verbose_name="帧率（fps）")  # 固定24fps
    price = models.DecimalField(max_digits=10, decimal_places=2, default=0.70, verbose_name="价格（元）")  # 添加价格字段
    
    # 辅助字段：方便回溯
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    is_deleted = models.BooleanField(default=False, verbose_name="是否删除")  # 软删除
    
    class Meta:
        verbose_name = 'AI视频制作'
        verbose_name_plural = 'AI视频制作'
        ordering = ['-create_time']
    
    def __str__(self):
        return f"用户{self.user.username}的任务：{self.volc_task_id}"
    
    def calculate_price(self):
        """根据视频参数计算价格"""
        # 价格表映射（分辨率_宽高比_时长 -> 价格）
        price_map = {
            # 480p
            '480p_16:9_5': 0.73, '480p_16:9_10': 1.46,
            '480p_4:3_5': 0.70, '480p_4:3_10': 1.41,
            '480p_1:1_5': 0.72, '480p_1:1_10': 1.44,
            '480p_21:9_5': 0.70, '480p_21:9_10': 1.40,  # 最便宜
            # 720p
            '720p_16:9_5': 1.54, '720p_16:9_10': 3.09,
            '720p_4:3_5': 1.64, '720p_4:3_10': 3.28,
            '720p_1:1_5': 1.62, '720p_1:1_10': 3.24,
            '720p_21:9_5': 1.69, '720p_21:9_10': 3.38,
            # 1080p
            '1080p_16:9_5': 3.67, '1080p_16:9_10': 7.34,
            '1080p_4:3_5': 3.65, '1080p_4:3_10': 7.30,
            '1080p_1:1_5': 3.65, '1080p_1:1_10': 7.29,
            '1080p_21:9_5': 3.55, '1080p_21:9_10': 7.10,
        }
        
        key = f"{self.resolution}_{self.aspect_ratio}_{self.duration}"
        return price_map.get(key, 0.70)  # 默认返回最便宜价格
    
    def save(self, *args, **kwargs):
        """保存时自动计算价格"""
        self.price = self.calculate_price()
        super().save(*args, **kwargs)
